<template>
  <IFexHeaderMain>
    <template #header>
      <IHeader>确认开柜</IHeader>
    </template>
    <view class="locker-page wh_auto">
      <!-- 网点信息栏 -->
      <view class="bgf" style="margin-bottom: 20rpx; padding-bottom: 20rpx">
        <view class="location-bar pd_20">
          <view class="location-info">
            <text class="location-title">{{ accountInfo.pointName }}{{ accountInfo.counterAlias }}</text>
          </view>
          <view class="rule-tag"> 24小时营业 </view>
        </view>
        <view class="pd_20 location-bar bar_dis">
          <view class="location-info">
            <view class="location-title_dis"> 免费寄存</view>
          </view>
          <view class="rule-tag_dis"> 可多次中途开门 </view>
        </view>

        <!-- 核心规则说明 -->
        <view class="mg_20 rule-card">
          <view class="rule-item">
            <text class="rule-number">1.</text>
            <text class="rule-text">当日22时前务必将所有物品取走</text>
          </view>
          <view class="rule-item">
            <text class="rule-number">2.</text>
            <text class="rule-text rule-text_read">为避免柜门无效占用，扫码需支付押金</text>
          </view>
          <view class="rule-item" style="margin-bottom: 0">
            <text class="rule-number">3.</text>
            <text class="rule-text rule-text_read">结束寄存后押金0-5个工作日退还，请务必关好柜门</text>
          </view>
        </view>
      </view>
      <!-- 柜门选择区 -->
      <view class="locker-select mg_20">
        <view class="select-label">请选择柜门</view>
        <view class="locker-info" v-if="roomInfo.userStorageId">
          <view class="locker-number locker-info_content">{{ roomInfo.doorNoStr }}</view>
          <view class="change-btn locker-info_content" @click="replaceCabinetFun">更换柜门 <uni-icons style="vertical-align: bottom" type="right" size="30" color="#f5222d"></uni-icons></view>
        </view>
        <view class="locker-number" style="text-align: center" v-else>没有空余的柜子</view>
      </view>

      <!-- 操作按钮 -->
      <view class="action-bar">
        <button class="open-btn" @click="payMsgFun">支付开门</button>
        <!-- <button open-type="liveActivity"  activity-type="1001" @createliveactivity="onLiveActivityCreate">支付开门11112</button> -->
      </view>
    </view>
    <uni-popup ref="popupRef" type="dialog" borderRadius="16rpx 16rpx 0 0">
      <view class="popup_price">
        <view class="popup_price-bar">
          <view class="location-info"> 找准柜门，请勿存错！ </view>
          <view class="rule-tag" @click="handleLoginClick('close')"> <uni-icons type="close" color="#f9f9f9" size="30"></uni-icons> </view>
        </view>
        <view class="popup_price_content">
          <view class="popup_price_content_one">{{ roomInfo.doorNoStr }}</view>
          <view class="popup_price_content_two">
            <view class="deposit-item" v-for="(item, index) in orderDetail.npList || []" :key="index">
              <text class="label">{{ item.amountType }}</text>
              <text class="value">¥{{ item.amount || 0 }}</text>
            </view>
          </view>
          <view class="popup_price_content_three">
            <view> 寄存结束后按规则结算 </view>
            <view> 剩余费用可在个人余额账户提现 </view>
          </view>
        </view>
        <button class="open-btn" @click="onSubmitFun">确认支付</button>
      </view>
    </uni-popup>
    <uni-popup ref="popupGMRef" type="dialog">
      <uni-popup-dialog cancelText="取消" type="info" confirmText="确定" title="更换柜门" @confirm="changeLocker" @close="handleLoginClick('close')">
        <view class="square-checkbox-group">
          <view v-for="(item, index) in replaceData.dataList" :key="index" class="square-checkbox" @click="changeSquareFun(item)">
            <view class="square-checkbox_row" :class="{ active: replaceData.active == item.value }"
              ><text>{{ item.text }}</text></view
            >
          </view>
        </view>
      </uni-popup-dialog>
    </uni-popup>
  </IFexHeaderMain>
</template>

<script setup lang="ts" name="index">
  import { computed, onMounted, ref } from 'vue'
  import ITabBar from '@/components/container/ITabBar.vue'
  import IFexHeaderMain from '@/components/container/IFexHeaderMain.vue'
  import IHeader from '@/components/container/IHeader.vue'
  import { onLoad } from '@dcloudio/uni-app'
  import { confirmOrder, getDeviceCabinet, getUserStorageById, reinitializeOrder, reinitializeOrderNew } from '@/api/index'
  import { useNavigatePage } from '@/hooks/navigateTo'
  import useAccountStore from '@/store/account'
  import useToastMsg from '@/hooks/sysMsg'
  import { wxPayFun } from '@/api/wxPay'
  import useUserInfoStore from '@/store/userInfo'
  import { subscribeMsg } from '@/utils'
  import { noAuthMessage, orderEnd } from '@/api/currentLocker'
import { getPlatformMsg } from '@/utils/platform'
  const popupRef = ref()
  const popupGMRef = ref()
  const toastMsg = useToastMsg()
  const accountStore = useAccountStore()
  const navigatePage = useNavigatePage()
  const userInfoStore = useUserInfoStore()
  const accountInfo = computed(() => accountStore.getAccountDetails)
  const userInfo = computed(() => userInfoStore.getUserInfo)
  const orderDetail = ref<any>({})
  const replaceData = ref<any>({
    active: '',
    dataList: [],
  })
  const roomInfo = ref({
    cabinetNo: '',
    doorNo: '',
    userStorageId: '',
    doorNoStr: '',
  })

  onLoad((options: any) => {
    roomInfo.value.cabinetNo = options.cabinetNo
    roomInfo.value.doorNo = options.doorNo
    roomInfo.value.userStorageId = options.userStorageId
    if (options.code == 0) {
      roomInfo.value.doorNoStr = options.doorNo + '柜'
    } else {
      roomInfo.value.doorNoStr = '没有空余柜子'
    }
  })
  const replaceCabinetFun = async () => {
    const result = await getDeviceCabinet(uni.getStorageSync('deviceId'))
    if (result) {
      handleGMLoginClick('open')
      replaceData.value.dataList = result.data.filter((item: any) => item.ip).map((item: any) => ({ text: item.ip, value: item.id }))
    }
  }

  const changeLocker = async () => {
    const result = await reinitializeOrderNew(roomInfo.value.userStorageId, replaceData.value.active)
    if (result && result.data.code == 0) {
      roomInfo.value.cabinetNo = result.data.cabinetNo
      roomInfo.value.doorNo = result.data.doorNo
      roomInfo.value.userStorageId = result.data.userStorageId
      roomInfo.value.doorNoStr = result.data.doorNo + '柜'
    } else {
      toastMsg.showToast('暂无可用柜子,请稍后重试')
    }
  }
  const changeSquareFun = (item: any) => {
    replaceData.value.active = item.value
  }
  const handleLoginClick = (type = 'open') => (type == 'close' ? popupRef.value.close() : popupRef.value.open('bottom'))
  const handleGMLoginClick = (type = 'open') => (type == 'close' ? popupGMRef.value.close() : popupGMRef.value.open())
  const payMsgFun = async () => {
    const subResult = await subscribeMsg(['W7VqrHBrs4q1XiQ3tDha41_Ucw68hBf5ougD0nIgX1o'])
    if (subResult === true) {
      noAuthMessage(userInfo.value.userId, '1')
    } else {
      noAuthMessage(userInfo.value.userId, '2')
    }
    payAndOpen()
  }
  const payAndOpen = async () => {
    if (roomInfo.value.userStorageId) {
      const result = await getUserStorageById(roomInfo.value.userStorageId)
      if (result) {
        orderDetail.value = result.data
        handleLoginClick()
      } else {
        toastMsg.showToast('获取柜子信息失败')
      }
    } else {
      toastMsg.showToast('无空闲柜子')
    }
  }
  const onSubmitFun = async () => {
    // toastMsg.showLoading('支付中...')
    let amount = 0
    orderDetail.value.npList.map((item: any) => {
      amount += item.amount || 0
    })
    if (amount == 0) {
      const result = await confirmOrder(roomInfo.value.userStorageId)
      if (result) {
        if (result.data.code == 0) {
          setTimeout(async () => {
            const result = await orderEnd(userInfo.value.userId, roomInfo.value.userStorageId, '2')
            if (result && result.code == 200) {
              // toastMsg.showToast('柜子已打开')
              toastMsg.showToast('寄存成功')
              navigatePage.redirectTo(`/pages/baoguo/index`)
            }
          }, 1000)
        }
      }
    } else {
      await wxPayFun({
        userId: userInfoStore.getUserInfo.userId,
        pointId: orderDetail.value.pointId,
        amount: amount,
        counterId: orderDetail.value.counterId,
        cabinetId: orderDetail.value.cabinetNo,
        userStorageId: roomInfo.value.userStorageId,
        type: '2', //1:押金，2：租金
      })
    }

    // toastMsg.hideLoading()
  }
  const onLiveActivityCreate = (e: any) => {
    console.log(e)
  }
  const paySubmitFun = async () => {
    const result = await confirmOrder(roomInfo.value.userStorageId)
    if (result) {
      if (result.data.code == 0) {
        toastMsg.showToast('寄存成功')
        navigatePage.redirectTo(`/pages/baoguo/index`)
        // navigatePage.redirectTo(`/pages/index/index`)
        // navigatePage.redirectTo(`/pages/confirmRoom/payDetail?userStorageId=` + roomInfo.value.userStorageId)
      }
    }
  }
</script>

<style scoped lang="scss">
  .popup_price_content_one {
    font-size: 80rpx;
    color: #e63946;
    font-weight: bold;
    display: block;
    margin-bottom: 20rpx;
  }
  .popup_price_content_two {
  }
  .popup_price_content_three {
    color: #ff9900;
    font-size: 30rpx;
  }
  .popup_price_content {
    position: relative;
    text-align: center;
    padding: 40rpx 0;
  }
  .poab {
    position: absolute;
    z-index: 999;
    font-size: 46rpx;
    color: #e63946;
  }
  .popup_price {
    background: #ffffff;
  }
  /* 页面基础样式 */
  .locker-page {
    // padding: 20rpx;
    background-color: #f1f1f1;
  }
  .bgf {
    background: #ffffff;
  }
  .mg_20 {
    margin: 0 20rpx;
  }
  .pd_20 {
    padding: 0 20rpx;
  }
  .price_logo {
    width: 80rpx;
    height: 80rpx;
  }

  /* 网点信息栏 */
  .popup_price-bar {
    display: flex;
    justify-content: space-between;
    align-items: center;
    background: #fafafa;
    padding: 20rpx;
    .location-info {
      font-size: 40rpx;
    }
  }
  /* 网点信息栏 */
  .location-bar {
    display: flex;
    justify-content: space-between;
    align-items: center;
    background: #fafafa;
    padding: 20rpx 10rpx 0 10rpx;
    margin-bottom: 20rpx;
    // border-radius: 16rpx;
    //
  }
  .location-title {
    font-size: 34rpx;
    font-weight: 700;
    color: #333;
  }
  .bar_dis {
    background-color: #3b82f6;
    padding: 20rpx 10rpx;
    // padding-left: 10rpx;
    // padding-right: 20rpx;
  }
  .price_logo {
    margin-right: 10rpx;
  }
  .location-title_dis {
    font-size: 50rpx;
    color: #f5222d;
    font-weight: 700;
  }
  .rule-tag_dis {
    color: #ffffff;
    font-size: 34rpx;
  }
  .rule-tag {
    color: #3b82f6;
    font-weight: 700;
    font-size: 34rpx;
  }
  .business-hours {
    font-size: 24rpx;
    color: #666;
    margin-top: 5rpx;
  }

  /* 规则说明卡片 */
  .rule-card {
    background: #fff8e1;
    border: 1px solid #ff9900;
    border-radius: 12rpx;
    padding: 20rpx;
    margin-bottom: 20rpx;
  }
  .rule-item {
    display: flex;
    align-items: flex-start;
    margin-bottom: 15rpx;
  }
  .rule-number {
    font-size: 28rpx;
    color: #ff9900;
    font-weight: bold;
    margin-right: 10rpx;
  }
  .rule-text {
    font-size: 30rpx;
    color: #666;
    font-weight: 700;
  }
  .rule-text_read {
    color: #f5222d;
  }

  /* 柜门选择区 */
  .locker-select {
    background: #fff;
    border-radius: 16rpx;
    padding: 20rpx;
    margin-bottom: 20rpx;
    box-shadow: 5rpx 4rpx 12rpx rgba(0, 0, 0, 0.2);
  }
  .select-label {
    font-weight: 600;
    font-size: 34rpx;
    font-weight: 700;
    color: #333;
    margin-bottom: 15rpx;
  }
  .locker-info {
    text-align: center;
  }
  .locker-info_content {
    font-size: 50rpx;
    margin-bottom: 20rpx;
  }
  .locker-type {
    color: #ff9900;
  }
  .locker-number {
    font-size: 100rpx;
    color: #3b82f6;
    font-weight: bold;
  }
  .change-btn {
    margin-left: 40rpx;
    color: #e63946;
  }

  /* 操作按钮 */
  .action-bar {
    padding: 10rpx 20rpx;
  }
  .open-btn {
    width: 100%;
    background: #3b82f6;
    color: #fff;
    font-size: 32rpx;
    border-radius: 12rpx;
    padding: 10rpx 0;
  }

  .deposit-tip {
    background: #fff;

    .tip-header {
      margin-bottom: 32rpx;
      text-align: center;

      .tip-title {
        font-size: 32rpx;
        color: #333;
        flex: 1;
      }
    }

    .main-info {
      text-align: center;
      margin-bottom: 32rpx;

      .cabinet-number {
        font-size: 80rpx;
        color: #e63946;
        font-weight: bold;
        display: block;
        margin-bottom: 24rpx;
      }

      .cabinet-img {
        width: 200rpx;
        height: auto;
      }
    }
  }
  .deposit-item {
    display: flex;
    justify-content: space-between;
    align-items: center;
    background: #f9f9f9;
    padding: 16rpx 24rpx;
    border-radius: 8rpx;
    margin-bottom: 16rpx;

    .label {
      color: #666;
      font-size: 28rpx;
    }
    .value {
      color: #e63946;
      font-size: 32rpx;
      font-weight: bold;
    }
  }
  .square-checkbox-group {
    display: flex;
    flex-wrap: wrap;
    width: 100%;
  }

  .square-checkbox {
    flex: 0 0 33.33%;
    max-width: 33.33%;
    box-sizing: border-box;
    padding: 10rpx;
  }
  .square-checkbox_row {
    display: flex;
    align-items: center;
    justify-content: center;
    height: 120rpx;
    width: 120rpx;
    background: #f5f5f5;
    border: 2rpx solid #e0e0e0;
    border-radius: 12rpx;
    font-size: 30rpx;
    color: #333;
  }
  .square-checkbox_row.active {
    border-color: #3b82f6;
    background: #e6f4ff; // 更贴合 #3b82f6 的浅蓝色
    color: #3b82f6;
  }
  :deep(.uni-icons) {
    vertical-align: bottom;
  }
</style>
